<template>
  <div class="vip-manage">
    <!-- 添加会员和批量添加按钮 -->
    <ul class="checknum">
      <li style="margin-left:20px;">
        会员总数 :
        <span style="color:#85ce61;">{{ total }}</span>
      </li>
      <li style="float:right;">
        <el-button
          type="success"
          style="padding:13px 20px;"
          @click="addVipUser"
        >添加新会员
        </el-button>
        <el-button
          type="success"
          style="padding:13px 20px;"
          @click="dialog.addMoreUser = true"
        >批量添加新会员
        </el-button>
      </li>
    </ul>

    <!-- 检索框 -->
    <div class="allsearch">
      <section class="search-content">
        <el-row :gutter="4" type="flex" justify="start">
          <el-col :span="24">
            <el-select
              v-model="listQuery.levelId"
              style="width:120px;"
              @change="manageMemberHandleFilter"
            >
              <el-option
                v-for="item in state"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
            <!--<el-select-->
            <!--v-model="listQuery.isExpire"-->
            <!--style="width:120px;"-->
            <!--@change="manageMemberHandleFilter"-->
            <!--&gt;-->
            <!--<el-option-->
            <!--v-for="item in viper"-->
            <!--:key="item.value"-->
            <!--:value="item.value"-->
            <!--:label="item.label"-->
            <!--/>-->
            <!--</el-select>-->
            <el-input
              v-model="listQuery.creator"
              style="width:220px;"
              placeholder="用户名"
              @keyup.enter.native="manageMemberHandleFilter"
            />
            <el-date-picker
              v-model="listQuery.daterange"
              :picker-options="picker"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="|"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width:300px"
            />
            <el-button type="primary" size="medium" @click="manageMemberHandleFilter">搜索</el-button>
            <el-button
              :loading="downloadLoading"
              size="medium"
              style="background-color:#e9ab3e;color:#fff;"
              @click="handleExport"
            >导出
            </el-button>
            <el-button size="medium" type="info" @click="clearParams">清空</el-button>
          </el-col>
        </el-row>
      </section>
    </div>

    <el-table
      :data="manageMemberList"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:15px;"
    >
      <el-table-column min-width="10%" align="center" label="用户名">
        <template slot-scope="scope">
          <span>{{ scope.row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="账号">
        <template slot-scope="scope">
          <span>{{ scope.row.account }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="等级">
        <template slot-scope="scope">
          <span>{{ scope.row.levelName }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="有效期">
        <template slot-scope="scope">
          <span v-if="scope.row.payType === 'year'">{{ scope.row.untilTime }}年</span>
          <span v-if="scope.row.payType === 'month'">{{ scope.row.untilTime }}个月</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="到期时间">
        <template slot-scope="scope">
          <span>{{ scope.row.expireTime }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="20%" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleClickEdit(scope)">编辑</el-button>
          <el-button type="danger" @click="handleClickCancel(scope)">取消</el-button>
          <el-button type="success" @click="handleClickHistory(scope)">历史</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />

    <!-- 添加新会员 -->
    <el-dialog :visible.sync="dialog.addUser" :before-close="cancelActiveUser" :title="dialog.edit ? '编辑' : '新增'" width="580px">
      <div class="addUser">
        <el-form ref="addUserForm" :model="eduUser" :rules="eduUserRules">
          <el-form-item :label-width="formLabelWidth" label="邮箱" prop="email">
            <el-input v-model="eduUser.email" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="账号" prop="account">
            <el-input v-model="eduUser.account" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="姓名" prop="name">
            <el-input v-model="eduUser.name" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="用户名" prop="nickName">
            <el-input v-model="eduUser.nickName" :disabled="dialog.edit" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="手机号" prop="verifiedMobile">
            <el-input v-model="eduUser.verifiedMobile" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密码" prop="password">
            <el-input v-model="eduUser.password" type="password" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="确认密码" prop="confirmPassword">
            <el-input v-model="eduUser.confirmPassword" type="password" style="width:300px;"/>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="用户类型" prop="userType">
            <el-select v-model="eduUser.userType" style="width:300px;">
              <el-option
                v-for="item in userType"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="用户权限">
            <el-checkbox-group v-model="roleIds">
              <el-checkbox
                v-for="role in allRoleList"
                :label="role.id"
                :key="role.id"
              >{{ role.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="会员等级" prop="levelId">
            <el-select v-model="eduUser.levelId" style="width:120px;">
              <el-option
                v-for="item in state"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="付费方式" prop="payType">
            <el-radio-group v-model="eduUser.payType">
              <el-radio label="year" aria-checked="true">按年</el-radio>
              <el-radio label="month">按月</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="开通时长" prop="untilTime">
            <el-input v-model="eduUser.untilTime" style="width:252px;"/>
            月(年)
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="activeUser === '1'" @click="cancelAddUser">取 消</el-button>
        <el-button v-if="activeUser === '1'" type="primary" @click="saveMemberInfo">确 定</el-button>
        <el-button v-if="activeUser === '2'" @click="cancelActiveUser">取 消</el-button>
        <el-button v-if="activeUser === '2'" type="primary" @click="addUser()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量添加新会员 -->
    <el-dialog :visible.sync="dialog.addMoreUser" title="批量添加新用户" width="580px">
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload"/>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <span v-if="dialogData.addMoreUser.loading">正在处理，请稍等......</span>
      </div>
    </el-dialog>

    <!-- 历史弹出框 -->
    <el-dialog :visible.sync="dialog.show" title="购买历史" width="1080px">
      <el-table
        :data="dialogData.historyData"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top:15px;"
      >
        <el-table-column min-width="10%" align="center" label="用户名">
          <template slot-scope="scope">
            <span>{{ scope.row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%" align="center" label="操作时间">
          <template slot-scope="scope">
            <span>{{ scope.row.operateTime.substring(0,10) }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%" align="center" label="到期时间">
          <template slot-scope="scope">
            <span>{{ scope.row.expireTime.substring(0,10) }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%" align="center" label="操作类型">
          <template slot-scope="scope">
            <span>{{ scope.row.operateType | statusFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%" align="center" label="会员等级">
          <template slot-scope="scope">
            <span>{{ scope.row.levelName }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%" align="center" label="开通时长">
          <template slot-scope="scope">
            <span>{{ scope.row.openingTime }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%" align="center" label="支付费用">
          <template slot-scope="scope">
            <span>{{ scope.row.paymentCost }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="dialog.total>0"
        :total="dialog.total"
        :page.sync="dialog.page"
        :limit.sync="dialog.limit"
        @handleSizeChange="dialogSizeChange"
        @handleCurrentChange="dialogCurrentChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialog.show = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // 分页组件
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import {addMoreVip, checkMemberExit, checkUserExit, deleteMemberUser, getEduxcloudMemberOperatePager, getEduxcloudMemberPager, getEduxcloudUserDic, getIsNotVipUserList, getVipLevel, saveOrUpdateEduxcloudUser, saveOrUpdateMemberUser} from '@/api/user/user' // 数据接口
  import {getTenantId, getUserId, getUserName} from '@/utils/auth'
  import {parseTime} from '@/utils'

  export default {
    components: {Pagination, UploadExcelComponent},
    filters: {
      statusFilter(status) {
        const statusMap = {
          buy: '购买',
          renew: '续费',
          promote: '升级',
          edit: '编辑',
          delete: '取消会员'
        };
        return statusMap[status]
      }
    },
    data() {
      var checkUser = (rule, value, callback) => {
        this.checkUser(value, callback)
      };
      const confirmPassword = (rule, value, callback) => {
        if (!this.eduUser.password) {
          callback(new Error('请先输入密码再进行确认'))
        } else if (!value) {
          callback(new Error('请输入确认密码'))
        } else {
          if (value !== this.eduUser.password) {
            callback(new Error('输入的密码不一致，请重新输入'))
          } else {
            callback()
          }
        }
      };
      return {
        activeUser: '2',
        eduUser: {},
        allRoleList: {},
        roleIds: [],
        downloadLoading: false,
        innerNameDialog: false,
        allList: [],
        edit: false,
        formLabelWidth: '100px',
        manageMemberList: [],
        total: 0,
        dialog: {
          addMoreUser: false,
          addUser: false,
          edit: false,
          show: false,
          total: 0,
          page: 1,
          limit: 5,
          userName: ''
        },
        dialogData: {
          addUser: {levelId: '', payType: 'year'},
          addMoreUser: {},
          historyData: []
        },
        listQuery: {
          levelId: '',
          isExpire: '',
          creator: '',
          daterange: '',
          page: 1,
          limit: 20
        },
        picker: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end])
              }
            }
          ]
        },
        state: [
          {
            label: '会员等级',
            value: ''
          }
        ],
        userList: [],
        tableLabel: [
          {
            label: '会员等级',
            width: '1',
            prop: 'level'
          },
          {
            label: '到期日期',
            width: '2',
            prop: 'untilTime'
          }
        ],
        levelNameFilter: [],
        tableData: [],
        userType: [
          {label: '学员', value: 'STUDENT'},
          {label: '教师', value: 'TEACHER'},
          {label: '管理员', value: 'MANAGER'}
        ],
        userNameChoose: 1,
        userNameTableData: [],
        addRules: {
          nickName: [
            {required: true, message: '不能为空', trigger: 'focus'},
            {validator: checkUser, trigger: 'blur'}
          ],
          levelId: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ],
          payType: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ],
          untilTime: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ]
        },
        eduUserRules: {
          email: [
            {required: true, message: '请输入邮箱地址', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
          ],
          account: [
            {required: true, message: '请输入账号', trigger: 'blur'},
            // {
            //   validator(rule, value, callback) {
            //     checkAccount(value).then(res => {
            //       if (res.data.result) {
            //         callback(new Error('账号已存在，请重新输入！'))
            //       } else {
            //         callback()
            //       }
            //     })
            //   },
            //   trigger: 'blur'
            // }
          ],
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          nickName: [
            {required: true, message: '请输入用户昵称', trigger: 'blur'},
            // {
            //   validator(rule, value, callback) {
            //     if (value) {
            //       checkUserExit(value).then(res => {
            //         if (res.data.item) {
            //           callback(new Error('昵称已存在，请重新输入！'))
            //         } else {
            //           callback()
            //         }
            //       })
            //     }
            //   },
            //   trigger: 'blur'
            // }
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          confirmPassword: [
            {validator: confirmPassword, trigger: 'blur'},
            {required: true, message: '请输入确认密码', trigger: 'blur'}
          ],
          verifiedMobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {min: 11, max: 11, message: '长度为11个字符', trigger: 'blur'},
            // {
            //   validator(rule, value, callback) {
            //     checkPhoneNumber(value).then(res => {
            //       if (res.data.result) {
            //         callback(new Error('手机号已被使用，请换一个手机号'))
            //       } else {
            //         callback()
            //       }
            //     })
            //   },
            //   trigger: 'blur'
            // }
          ],
          userType: [
            {required: true, message: '用户类型不能为空', trigger: 'blur'}
          ],
          levelId: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ],
          payType: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ],
          untilTime: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    mounted() {
      this.getManageMemberList();
      this.initUserDic();
      this.initVipLevel()
    },
    methods: {
      checkUser(nickName, callback) {
        if (this.dialogData.addUser.id) {
          callback()
        }
        if (nickName) {
          checkUserExit(nickName).then(res => {
            if (res.data.item) {
              checkMemberExit(res.data.item.id).then(member => {
                if (!member.data.item) {
                  callback()
                } else {
                  callback(new Error('此用户已有会员，请勿重复添加！'))
                }
              })
            } else {
              callback(new Error('用户不存在，请先创建用户！'))
            }
          })
        }

      },
      initUserDic() {
        getEduxcloudUserDic(getTenantId()).then(response => {
          this.allRoleList = response.data.roleList
        })
      },
      // 查看历史按钮
      handleClickHistory(scope) {
        this.dialog.userName = scope.row.nickName;
        this.getEduxcloudMemberOperatePager();
        this.dialog.show = true
      },
      getEduxcloudMemberOperatePager() {
        const params = {};
        params.userName = this.dialog.userName;
        params.page = this.dialog.page;
        params.limit = this.dialog.limit;
        getEduxcloudMemberOperatePager(params).then(res => {
          this.dialogData.historyData = res.data.items;
          this.dialog.total = res.data.total
        })
      },
      // 上传文件
      beforeUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (isLt1M) {
          return true
        }
        this.$message({
          message: '请不要上传大小超过1M的文件',
          type: 'warning'
        });
        return false
      },
      handleSuccess({results, header}) {
        this.dialogData.addMoreUser.loading = true;
        for (const index in results) {
          if (results[index].nickName) {
            checkUserExit(results[index].nickName).then(res => {
              const num = Number(index) + 1;
              if (res.data.item) {
                checkMemberExit(res.data.item.id).then(member => {
                  if (member.data.item) {
                    this.$message.error(`第${num}个用户已为会员，请勿重复添加！`)
                  } else {
                    results[index].userId = res.data.item.id;
                    results[index].tenantId = getTenantId();
                    if (num === results.length && this.levelNameFilter.indexOf(results[index].levelName) !== -1) {
                      addMoreVip(results).then(res => {
                        this.$notify({title: '成功', message: '批量导入完成', type: 'success', duration: 2000});
                        this.getManageUserList()
                      })
                    }
                  }
                })
              } else {
                this.$message.error(`第${num}个用户不存在，请先创建用户！`)
              }
            })
          }
        }
        this.dialogData.addMoreUser.loading = false;
        this.dialog.addMoreUser = false
      },
      handleClickCancel(scope) {
        this.$confirm(`确定取消${scope.row.nickName}的会员吗`, '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteMemberUser(scope.row.id, scope.row.userId).then(res => {
            this.$notify({title: '成功', message: `${scope.row.nickName}的会员取消成功`, type: 'success', duration: 2000});
            this.getManageMemberList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          })
        })
      },
      saveMemberInfo() {
        this.$refs['addMemberForm'].validate((valid) => {
          if (valid) {
            this.dialogData.addUser.tenantId = getTenantId();
            saveOrUpdateMemberUser(this.dialogData.addUser).then(res => {
              this.dialogData.addUser = {};
              let title = '';
              if (res.data.type === 'error') {
                title = '失败'
              } else if (res.data.type === 'success') {
                title = '成功'
              }
              this.$notify({title: `${title}`, message: `${res.data.message}`, type: `${res.data.type}`, duration: 2000});
              this.getManageMemberList()
            });
            this.dialog.addUser = false;
            this.$refs['addMemberForm'].resetFields()
          }
        });
      },
      getManageMemberList() {
        const params = {};
        params.levelId = this.listQuery.levelId;
        if (this.listQuery.daterange !== undefined && this.listQuery.daterange != null) {
          params.startDate = this.listQuery.daterange[0];
          params.endDate = this.listQuery.daterange[1]
        }
        params.isExpire = this.listQuery.isExpire;
        params.nickName = this.listQuery.creator;
        params.page = this.listQuery.page;
        params.limit = this.listQuery.limit;
        params.tenantId = getTenantId();
        getEduxcloudMemberPager(params).then(response => {
          this.manageMemberList = response.data.items;
          this.allList = response.data.items;
          this.total = response.data.total;
          this.manageMemberList.map(item => {
            item.confirmPassword = item.password
          })
        })
      },
      initVipLevel() {
        getVipLevel().then(response => {
          let vipLevelList = response.data.vipLevelList;
          for (const item in vipLevelList) {
            this.state.push({'value': vipLevelList[item].id, 'label': vipLevelList[item].name});
            this.levelNameFilter.push(vipLevelList[item].name)
          }
        })
      },
      initUserList() {
        getIsNotVipUserList(getTenantId()).then(res => {
          this.userList = res.data.items;
          this.userList.map(item => {
            item.confirmPassword = item.password
          })
        })
      },
      // 导出按钮
      handleExport() {
        this.downloadLoading = true;
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['用户名', '等级', '到期时间'];
          const filterVal = ['nickName', 'levelName', 'expireTime'];
          const list = this.allList;
          const data = this.formatJson(filterVal, list);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'vipList',
            autoWidth: true,
            bookType: 'xlsx'
          });
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'expireTime') {
            return v[j] ? parseTime(v[j]) : v[j]
          } else {
            return v[j]
          }
        }))
      },
      // 数据检索
      manageMemberHandleFilter() {
        this.getManageMemberList()
      },
      clearParams() {
        this.listQuery.daterange = [];
        this.listQuery.isExpire = '';
        this.listQuery.creator = '';
        this.listQuery.levelId = '';
        this.getManageMemberList()
      },
      // 改变分页页数
      handleSizeChange(val) {
        this.listQuery.page = 1;
        this.listQuery.limit = val.value;
        this.getManageMemberList()
      },
      // 改变当前页
      handleCurrentChange(val) {
        this.listQuery.page = val.value;
        this.getManageMemberList()
      },
      dialogSizeChange(val) {
        this.dialog.page = 1;
        this.dialog.limit = val.value;
        this.getEduxcloudMemberOperatePager()
      },
      dialogCurrentChange(val) {
        this.dialog.page = val.value;
        this.getEduxcloudMemberOperatePager()
      },
      addUser() {
        this.$refs['addUserForm'].validate((valid) => {
          if (valid) {
            this.eduUser.creatorId = getUserId();
            this.eduUser.creatorName = getUserName();
            this.eduUser.tenantId = getTenantId();
            this.eduUser.roleIds = this.roleIds.toString();
            saveOrUpdateEduxcloudUser(this.eduUser).then(res => {
              saveOrUpdateMemberUser(this.eduUser).then(res => {
                this.getManageMemberList();
                this.eduUser = {};
                this.$notify({title: '成功', message: '创建成功', type: 'success', duration: 2000})
              })
            });
            this.dialog.addUser = false
          }
        })
      },
      addVipUser() {
        this.eduUser = {};
        this.dialog.addUser = true;
        this.edit = false;
        this.dialog.edit = false;
        this.dialogData.addUser = {levelId: '', payType: 'year'};
        this.initUserList();
      },
      handleClickEdit(scope) {
        this.dialog.addUser = true;
        this.dialog.edit = true;
        this.initUserList();
        this.eduUser = Object.assign({}, scope.row);
      },
      cancelActiveUser() {
        this.dialog.addUser = false;
        this.$refs.addUserForm.clearValidate();
        this.eduUser = {}
      },
      cancelAddUser() {
        this.dialog.addUser = false;
        this.$refs.addMemberForm.resetFields();
        this.eduUser = {}
      }
    }
  }
</script>

<style lang="scss">
  .vip-manage {
    .checknum {
      list-style: none;
      padding: 0 0 0 11px;
      margin: 6px 0 20px;
      height: 70px;
      line-height: 70px;
      box-sizing: border-box;
      background-color: #f8f8f8;

      li {
        float: left;
        display: block;
        margin-right: 20px;
        color: #72726f;
      }
    }

    .allsearch {
      margin-top: 0;
      padding: 0;

      .search-content {
        width: 100%;
      }
    }

    .el-dialog {
      border-radius: 6px;
    }

    .addUser {
      /deep/ .el-tabs__header {
        margin: -20px 0 20px;
      }
    }
  }
</style>
